<template>
  <div id="purposeDetailDiv">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" :disabled="isEmpty(purposeId)" @click="findPurposeDetailList"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="isEmpty(purposeId)" @click="addPurposeDetail"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :disabled="isEmpty(purposeId)" @click="saveBathPurposeDetail"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="isEmpty(purposeId)" @click="deletePurposeDetail"></vxe-button>
      </template>
    </vxe-toolbar>

    <div class="tableBox">
      <vxe-table ref="purposeDetailTableRef" class="mytable-scrollbar" border="inner" align="left" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="detailList" :loading="rloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
        <vxe-column type="checkbox" width="30"></vxe-column>
        <vxe-column field="seq" title="序号" width="50" :edit-render="{}">
          <template #edit="{ row, rowIndex, column }">
            <vxe-input v-model="row.seq" type="number"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="sampleTypeCode" title="code" :edit-render="{}">
          <template #default="{ row }">
            <span>{{ row.sampleTypeCode }}</span>
          </template>
        </vxe-column>
        <vxe-column field="sampleTypeName" title="标本类型" :edit-render="{}">
          <template #default="{ row }">
            <span>{{ row.sampleTypeName }}</span>
          </template>
          <template #edit="{ row, rowIndex }">
            <VxePulldownSelectionWithNa style="width: 100%" :isChild="true" :url="'/api/lab/labSampleType/findSampleTypeList'" :childIndex="rowIndex" @confirmClick="SelectRowClick" :tableColumn="[
                      { type: 'seq', title: '#', width: '30px' },
                      { field: 'sampleTypeCode', title: '编码' },
                      { field: 'sampleTypeName', title: '名称',width:'60px' }
                    ]" :aimKeys="[
                      { aimKey: 'sampleTypeId', rowKey: 'id' },
                      { aimKey: 'sampleTypeCode', rowKey: 'sampleTypeCode' },
                      { aimKey: 'sampleTypeName', rowKey: 'sampleTypeName' }
                    ]" :displayTexts="['sampleTypeName']" :displayTextObj="row.sampleTypeName ? row.sampleTypeName : ''" />
          </template>
        </vxe-column>

      </vxe-table>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import { AppStore } from '@/stores/store';
import SelectDataGrid from '@/components/SelectDataGrid.vue';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';

let store = AppStore();
defineExpose({ initPage });
let purposeId = null;
let purposeNo = null;
let detailList: any = reactive([]);
let rloading = ref(false);

function initPage(row: any) {
  purposeId = row.id;
  purposeNo = row.purposeNo;
  findPurposeDetailList();
  getCultureCombinationList();
}
async function getCultureCombinationList() {
  const url = '/api/bac/bac-cultrue-combination/findBacCultureCombinationList';
  const data = await proxy.$http.get(url);
}

// 获取左侧仪器表格数据+刷新+右侧表格数据
function findPurposeDetailList() {
  rloading.value = true;
  detailList.length = 0; //放入数据前清空数据
  if (isEmpty(purposeId)) {
    rloading.value = false;
    return;
  }
  const url = '/api/bac/bacReqPurposeSampletype/findPurposeSampletypeList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { purposeId: purposeId, purposeNo: purposeNo }
    })
    .then((res: any) => {
      detailList.push(...res.data);
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('数据异常', VxeNotifyType.error);
    });
}

function addPurposeDetail() {
  if (isEmpty(purposeId)) {
    VxeMessage('请选择目的', VxeNotifyType.error);
  } else {
    const record: any = {
      id: '',
      purposeId: purposeId,
      purposeNo: purposeNo,
      sampleTypeCode: '',
      seq: detailList.length + 1,
      orgId: store.userInfo.orgId
    };
    detailList.push(record);
  }
}

// 左侧保存
async function saveBathPurposeDetail() {
  if (isEmpty(purposeId)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.purposeDetailTableRef;
    if ($Xtable) {
      if (detailList.length > 0) {
        const url = '/api/bac/bacReqPurposeSampletype/addPurposeSampletype';
        proxy.$http
          .post(url, detailList)
          .then((res: any) => {
            VxeMessage('更新成功', VxeNotifyType.success);
            findPurposeDetailList();
          })
          .catch((err: any) => {
            VxeMessage('更新失败', VxeNotifyType.success);
          });
      } else {
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}
// 左侧删除
function deletePurposeDetail() {
  const sltDetails = (proxy.$refs.purposeDetailTableRef as any).getCheckboxRecords();
  if (!(sltDetails.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delDetailList = sltDetails.filter((p: any) => !isEmpty(p.id));
        if (delDetailList.length > 0) {
          const url = '/api/bac/bacReqPurposeSampletype/deleteBatchPurposeSampletype';
          proxy.$http
            .post(url, delDetailList)
            .then((res: any) => {
              findPurposeDetailList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeDetailList = sltDetails.filter((p: any) => isEmpty(p.id));
        if (removeDetailList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.purposeDetailTableRef;
          if ($Xtable) {
            for (const removeRow of removeDetailList) {
              detailList.splice(removeRow.seq - 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
// 获取组件当前行数据
function selectSampleTypeRow(row, index) {
  detailList[index].sampleTypeName = row.sampleTypeName;
  detailList[index].sampleTypeId = row.id;
  detailList[index].sampleTypeCode = row.sampleTypeCode;
}
function SelectRowClick(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      detailList[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}
</script>

<style lang="scss" scoped>
#purposeDetailDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }
}
</style>
